# 导入视图类
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from Apis.serializers import ProductModelSerializer
from product.models import Product
from rest_framework.authentication import BasicAuthentication, SessionAuthentication, TokenAuthentication
from rest_framework.permissions import IsAuthenticated,AllowAny,IsAdminUser
from Drf_api.paginations import ProductPageNumberPagination
# Create your views here.

# 访问数据，需要认证用户身份，通过认证，才能访问数据
class ProductApiView(APIView):
    # 传入分页器类  
    pagination_class = ProductPageNumberPagination
    # 认证用户
    authentication_classes = [BasicAuthentication]
    # 权限类
    permission_classes = [IsAuthenticated]
    # 限流 视图级别优先级高
    throttle_scope = "product"

    # Authorization: Basic emhhbmdzYW46MTIzNDU2 Basic认证 + 用户名和密码的base64编码

    def get(self, request):
        # 获取查询参数
        request.query_params.get('pk')
        
        # 获取路径参数 ?product_name=小米14pro
        # product_name = request.query_params.get('product_name')
        # print(product_name)
        # Product.objects.filter(product_name=product_name)
        # 通过request.user来获取当前请求的用户对象
        user = request.user.id
        # 根据模型查询数据
        product = Product.objects.all()

        # 调用分页器  分页一般是作为列表的时候处理
        paginator = self.pagination_class()
        # 对分页数据进行筛选
        page = paginator.paginate_queryset(product, request)

        # 对分页数据处理
        if page is not None:
            ser = ProductModelSerializer(page, many=True)
            # 返回分页数据响应
            return paginator.get_paginated_response(ser.data)

        # 把查询到的数据传递给序列化器进行处理
        ser = ProductModelSerializer(product, many=True)
        # 返回响应
        return Response(ser.data, status=status.HTTP_200_OK)
    
    def post(self, request):
        # 1.获取前端传递过来的数据
        # {'product_name': '小米yu127', 'price': 100, 'popularity': 10500, 'stock': 1000, 'is_active': True}
        # data  = request.data
        ser = ProductModelSerializer(data=request.data)
        # 2.把数据传递给序列化器进行处理
        # 3.保存数据
        if ser.is_valid(raise_exception=True):
            # 保存数据
            ser.save()
            # 4.返回响应
            return Response({"message": "商品添加成功!", "data": ser.data}, status=status.HTTP_201_CREATED)
       